#批量获取音乐小案例
from urllib.parse import unquote,quote
from fake_useragent import UserAgent
import requests
import random
import re
import time
file_path = r"C:\Users\a2038\Desktop\爬虫文件夹\音乐\test"
music_num = 268449
for i in range(1,11):
    time.sleep(1)
    url =f"https://www.yymp3.com/Play/23350/{music_num}.htm"
    headers = {"User-Agent":UserAgent().random}
    res = requests.get(url,headers=headers)
    try:
        music_path = re.search(r'song_data.0.{3}[^"]*.', res.content.decode())
        music_path = re.findall(r'[|][^|]*', music_path.group())
        music_path = re.search(r"\w[^.]*.", music_path[3])
        music_path = music_path.group() + "mp3"
        url = "https://ting8.yymp3.com/" + music_path
        headers = {"User-Agent": UserAgent().random}
        res = requests.get(url, headers=headers)
        with open(file_path + f"{i}.mp3", "wb") as f:
            f.write(res.content)
        music_num += 1
        print(music_num)
    except Exception as e:
        print(e)
        print("报错已停止运行,可能原因: 网站访问失败")
        break
